<script setup lang="ts">
import { computed } from 'vue';

import { ApiComponent } from '@vben/common-ui';

import ApiView from '#/components/view/api-view.vue';
import { withCache } from '#/store/api-cache';

const props = defineProps<{
  /** 获取options数据的函数 */
  api?: ((arg?: any) => Promise<any[] | Record<string, any>>) | string;
  cacheExpireTime?: number;
  childrenField?: string;
  labelField?: string;
  /** 传递给api的参数 */
  params?: Record<string, any>;
  // 请求方式
  requestMethod?: 'get' | 'post';
  value?: Array<number | string> | null | number | string | undefined;
  valueField?: string;
}>();

const emit = defineEmits<{
  (
    e: 'update:value',
    value: Array<number | string> | null | number | string | undefined,
  ): void;
}>();

// 使用 computed 缓存 withCache 实例
const withCacheApi = computed(() => {
  return withCache(props.api, {
    expireTime: props.cacheExpireTime,
    requestMethod: props.requestMethod,
  }) as any;
});

const value = computed({
  get() {
    return props.value;
  },
  set(val) {
    emit('update:value', val);
  },
});
</script>

<template>
  <ApiComponent
    v-if="value"
    v-model="value"
    model-prop-name="value"
    :api="withCacheApi"
    :request-method="requestMethod"
    :params="{
      ...params,
      __value__: value,
      includeType: 2,
      includeIds:
        $attrs.mode === 'multiple' ||
        (typeof value === 'string' && value?.includes(','))
          ? typeof value === 'string'
            ? value.split(',')
            : value
          : [value],
    }"
    :component="ApiView"
    :label-field="labelField"
    :value-field="valueField"
    :children-field="childrenField"
  />
</template>
